import type { PropType } from "vue";
import type { ColumnFilter, IconClass } from "../../types";
import { ElMessage } from "element-plus";
import { computed, defineComponent, inject, nextTick, onMounted, ref } from "vue";
import { $t } from "@/plugins/i18n";
import { SYMBOL_INIT_SLOTS, SYMBOL_SET_FILTERED_SLOTS } from "../../types";

interface Props {
    iconClass: IconClass;
}

export default defineComponent((props: Props) => {
    const { iconClass } = props;
    const slots = inject(SYMBOL_INIT_SLOTS)!;
    const setFilteredSlots = inject(SYMBOL_SET_FILTERED_SLOTS)!;

    // 列筛选相关状态
    const columnFilters = ref<ColumnFilter[]>([]);
    const showColumnFilter = ref(false);

    /** 从插槽中获取列配置 */
    const getColumnsFromSlots = (): void => {
        const defaultSlot = slots.default?.();
        if (defaultSlot && Array.isArray(defaultSlot)) {
            const columns: ColumnFilter[] = [];
            defaultSlot.forEach((node: any) => {
                // 只处理 ElTableColumn 组件
                if (node.type?.name === "ElTableColumn") {
                    const props = node.props || {};
                    if (props.prop && props.label) {
                        columns.push({
                            prop: props.prop,
                            label: props.label,
                            visible: true,
                        });
                    }
                }
            });
            columnFilters.value = columns;
        }
    };

    /** 过滤后的插槽内容 */
    const filteredSlotsComputed = computed(() => {
        const defaultSlot = slots.default;
        if (!defaultSlot || columnFilters.value.length === 0) {
            return slots;
        }

        return {
            ...slots,
            default: () => {
                const nodes = defaultSlot();
                return filterColumnNodes(nodes);
            },
        };
    });

    /** 递归过滤列节点 */
    const filterColumnNodes = (nodes: any[]): any[] => {
        if (!Array.isArray(nodes)) return nodes;

        return nodes.filter((node: any) => {
            if (node.type?.name === "ElTableColumn") {
                const props = node.props || {};
                if (props.prop) {
                    const filter = columnFilters.value.find(f => f.prop === props.prop);
                    return filter ? filter.visible : true;
                }
            }
            return true;
        });
    };

    /** 重置列筛选 */
    const resetColumnFilter = (): void => {
        columnFilters.value.forEach((filter) => {
            filter.visible = true;
        });
    };

    /** 切换单列显示状态 */
    const toggleColumn = (prop: string): void => {
        const filter = columnFilters.value.find(f => f.prop === prop);
        if (filter) {
            const lastVisible = columnFilters.value.every((f) => {
                if (f.prop === prop) return true;
                return !f.visible;
            });
            if (lastVisible) {
                ElMessage({
                    message: $t("description.tableAtLeastOneColumn"),
                    type: "warning",
                });
                return;
            }
            filter.visible = !filter.visible;
        }
    };

    onMounted(() => {
        nextTick(() => {
            getColumnsFromSlots();
            setFilteredSlots(filteredSlotsComputed.value);
        });
    });

    return () => (
        <el-popover
            placement="right"
            width={160}
            trigger="click"
            v-model:visible={showColumnFilter.value}
        >
            {{
                reference: () => (
                    <span
                        class={`icon-[ri--filter-off-line] ${iconClass}`}
                        v-tippy={{ content: $t("button.columnFilter") }}
                    />
                ),
                default: () => (
                    <div class="column-filter-panel">
                        <div class="mb-3 pb-2 border-b border-solid border-[var(--el-border-color-light)]">
                            <div class="flex items-center justify-between">
                                <span class="font-medium text-sm">{$t("button.columnFilter")}</span>
                                <el-button
                                    type="primary"
                                    size="small"
                                    onClick={resetColumnFilter}
                                >
                                    {$t("button.reset")}
                                </el-button>
                            </div>
                        </div>
                        <div class="max-h-64 overflow-y-auto ep-scrollbar">
                            <div class="space-y-1">
                                {columnFilters.value.map(filter => (
                                    <div
                                        key={filter.prop}
                                        class="flex items-center px-1 py-1 hover:bg-gray-50 dark:hover:bg-gray-800 rounded transition-colors"
                                    >
                                        <el-checkbox
                                            modelValue={filter.visible}
                                            onChange={() => toggleColumn(filter.prop)}
                                            class="w-full"
                                        >
                                            <div class="text-sm truncate max-w-[100px] overflow-hidden" title={filter.label || filter.prop}>
                                                {filter.label || filter.prop}
                                            </div>
                                        </el-checkbox>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                ),
            }}
        </el-popover>
    );
}, {
    name: "ColumnFilter",
    props: {
        iconClass: {
            type: String as PropType<IconClass>,
            required: true,
        },
    },
});
